<?php
namespace app\flash\controller;
use think\Controller;
use think\Db;
use redis\RedisPackage;
use think\Common;
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
header('Access-Control-Allow-Methods: POST,GET','OPTIONS');
/**
 * 币世界注册登录操作接口
 * 
 */
class Login extends Controller
{
    /**
     * 功能：币世界注册操作接口
     * 时间：2019/08/08
     * 作者：张仕虎
     */
    public function  register(){
        $data = input('post.');
        $validate = new \app\flash\validate\User;
        if (!$validate->check($data)) {
            return json(msg(0, '', $validate->getError()));
        }
        RedisPackage::getInstance();
        $code = RedisPackage::get('register'.$data['phone']);
        if ($data['code'] !=$code) {
            return json(msg(0,'','验证码错误'));
        }
        $userData = [];
        $userData['password']       = md5($data['password']);
        $userData['phone']          = $data['phone'];
        $userData['rand_id']        = rands();
        $userData['create_time']    = strtotime(date('Y-m-d H:i:s'));
        $userData['newpassword']    = md5($data['newpassword']);
        $userData['picture']        = '123456.png';
        if ($userData['password'] != $userData['newpassword']) {
            return json(msg(0, '', '密码与确认密码不一致'));
        }
        unset($userData['newpassword']);
        $res = Db::table('user')->where('phone',$userData['phone'])->find();
        if ($res) {
            return json(msg(0, '', '此手机号已注册'));
        }
        // if ($res['password']) {
        //     unset($res['password']);
        //     $userData['pwdstatus'] = 1;
        // }else{
        //     unset($res['password']);
        //     $userData['pwdstatus'] = 2;
        // }
        if (empty($res['username'])) {
            $res['username'] = $res['phone'];
        }
        unset($res['create_time']);  
        $result = Db::table('user')->insert($userData);
        if ($result) {
            return json(msg(1, '', '注册成功'));
        }else{
            return json(msg(0, '', '注册失败'));
        }
    }
    /**
     * 功能：币世界登录操作接口
     * 时间：2019/08/08
     * 作者：张仕虎
     */
    public function login(){
        if (Request()->isPost()) {
            $data = input('post.');
            $data['password'] = md5($data['password']);
            // $data['phone'] = intval($data['phone']);
            // var_dump($data);die;
            $res = db('user')->where(['phone'=>$data['phone']])->find();
            if (!$res) {
                return json(msg(0,'','无此用户'));
            }
            if ($res['password'] !== $data['password']) {
                return json(msg(0,'','密码错误'));
            }
            $token = md5($res['id'].'token_salt').$res['id'];
            // var_dump($token);die;
            RedisPackage::getInstance();
           $true = RedisPackage::set('ht_'.$res['id'],$token,86400);
            if (!$true) {
                return json(0,'','token生成失败');
            }
            if ($res['password']) {
                unset($res['password']);
                $res['pwdstatus']  = 1;
            }else{
                unset($res['password']);
                $res['pwdstatus']  = 2;
            }
            if (empty($res['username'])) {
                $res['username'] = $res['phone'];
            }
            unset($res['create_time']);
            return json(msg(1,compact('res','token'),'登录成功'));
        }else{
           return json(msg(0,'','请求方式应为post请求'));
        }
    }
    /**
     * 退出登录
     * 
     * 
     */
    public function outlogin(){
        $phone  = input('phone');
        $id     = input('id');//用户id
        if (empty($phone) || empty($id)) {
            return json(msg(0,'','用户信息错误'));
        }
        RedisPackage::getInstance();
        $res = Db::table('user')->where(['id'=>$id,'phone'=>$phone])->find();
        if (!$res) {
            return json(msg(0,'','用户不存在'));
        }
        $key = 'ht_'.$res['id'];
        $true = RedisPackage::del($key);
        if ($true) {
            return json(msg(1,'','退出成功'));
        }else{
            return json(msg(0,'','登录失效'));
        }
    }
     /**
     * 手机号登录
     * 
     * 
     */
    public function phonelogin(){
        $phone = input('phone');
        $codes  = input('code');
        if (empty($phone)) {
            return json(msg(0,'','手机号不能为空'));
        }
        if(!preg_match("/^1[34578]\d{9}$/", $phone)){
            return json(msg(0,'','请输入正确的手机号'));
        }
        RedisPackage::getInstance();
        $code = RedisPackage::get('login'.$phone);
        if ($codes !=$code) {
            return json(msg(0,'','验证码错误'));
        }
        $res = Db::table('user')->where('phone',$phone)->find();
        if ($res) {
            $token = md5($res['id'].'token_salt').$res['id'];
            $true = RedisPackage::set('ht_'.$res['id'],$token,86400);
            if (!$true) {
                return json(msg(0,'','token生成失败'));
            }
            if ($res['password']) {
                unset($res['password']);
                $res['pwdstatus'] = 1;
            }else{
                $res['username'] = $res['phone'];
                unset($res['password']);
                $res['pwdstatus'] = 2;
            }
            if (empty($res['username'])) {
                $res['username'] = $res['phone'];
            }
            unset($res['create_time']);
            return json(msg(1,compact('res','token'),'登录成功'));
        }else{
            $insert['phone'] = $phone;
            $insert['create_time'] = strtotime(date('Y-m-d H:i:s'));
            $insert['rand_id']     = rands();
            $insert['picture']     = '123456.png';
            $true = Db::table('user')->insert($insert);
            if ($true) {
                $token = md5($res['id'].'token_salt').$res['id'];
                $token  = RedisPackage::set('ht_'.$res['id'],$token,86400);
                $res = Db::table('user')->where('phone',$phone)->find();
                if ($res['password']) {
                    unset($res['password']);
                    $res['pwdstatus'] = 1;
                }else{
                    unset($res['password']);
                    $res['pwdstatus'] = 2;
                }
                if (empty($res['username'])) {
                    $res['username'] = $res['phone'];
                }
                unset($res['create_time']);
                return json(msg(1,compact('res','token'),'登录成功'));
            }else{
                return json(msg(0,'','登录失败'));
            }
        }
        
    }
    /**
     * 功能：找回密码
     * 时间：2019/08/15
     * 作者：张仕虎
     */
    public function findpassword(){
        $phone = input('phone');//手机号
        $code  = input('code');//验证码
        $password = input('password');//新密码
        $newpassword = input('newpassword');//确认密码
        if (empty($phone)) {
            return json(msg(0,'','手机号不能为空'));
        }
        RedisPackage::getInstance();
        $key = 'findpassword'.$phone;
        $res = RedisPackage::get($key);
        if ($code !=$res) {
            return json(msg(0,'','验证码错误'));
        }
        if (empty($password)) {
            return json(msg(0,'','新密码不能为空'));
        }
        if (empty($newpassword)) {
            return json(msg(0,'','确认密码不能为空'));
        }
        if ($password != $newpassword) {
            return json(msg(0,'','新密码必须和确认密码一致'));
        }
        $return = Db::table('user')->where('phone',$phone)->find();
        if (empty($return)) {
            return json(msg(0,'','此用户不存在'));
        }
        if ($return['password'] == md5($password)) {
            return json(msg(0,'','新密码不能和近期密码一致'));
        }
        if ($return['password']) {
            unset($return['password']);
            $return['pwdstatus'] = 1;
        }else{
            unset($return['password']);
            $return['pwdstatus'] = 2;
        }
        if (empty($return['username'])) {
            $return['username'] = $return['phone'];
        }
        unset($return['create_time']);
        $password = md5($password);
        $data = Db::table('user')->where('phone',$phone)->update(['password'=>$password]);
        if ($data) {
            $token = md5($return['id'].'token_salt').$return['id'];
            $token  = RedisPackage::set('ht_'.$return['id'],$token,86400);
            return json(msg('1',compact('return','token'),'重置密码成功'));
        }else{
        return json(msg(0,'','重置密码失败'));
        }
    }
    /**
     * 账户设置短信验证码
     * 
     */
    public function sendcode(){
        $phone = input('phone');//手机号
        $type  = input('type');//类型 updatepwd-修改密码 updatephone-修改手机号(第二次验证码) upphone-修改手机号(第一次验证码) login-登录 register-注册账户 findpassword-找回密码
        if (empty($phone)) {
            return json(msg(0,'','手机号不能为空'));
        }
        RedisPackage::getInstance();
        $k = $phone.date('Y-m-d');
        $tre = RedisPackage::get($k);
        if ($tre) {
            if ($tre>3) {
                $k = $phone.date('Y-m-d');
                $value = $tre;
                RedisPackage::get($k,$value,'1800');
                return json(msg(0,'','对不起，请求次数太多，请30分钟后再试'));
            }else{
                $k = $phone.date('Y-m-d');
                $value += 1;
                RedisPackage::get($k,$value); 
            }
        }
        $Ucpaas = new \app\flash\validate\Ucpaas($phone);
        $appid = "bf1c1e29c7fe4882897a6b0990bd9d83";	//应用的ID，可在开发者控制台内的短信产品下查看
        $templateid ='';//可在后台短信产品→选择接入的应用→短信模板-模板ID，查看该模板ID
        if (empty($type)) {
            return json(msg(0,'','类型不能位空'));
        }
        if ($type == 'updatepwd') {
            $templateid = '494399';
        }
        if ($type == 'updatephone' || $type == 'upphone') {
            $templateid = '494159';
        }
        if ($type == 'login') {
            $templateid = '494367';
        }
        if ($type == 'register') {
            $templateid = '494401';
        }
        if ($type == 'findpassword') {
            $templateid = '494368';
        }
        // $param= \strval(rand(1000,9999));
        $param   = '12346';
        // $ress = $Ucpaas->SendSms($appid,$templateid,$param,$phone,'');
        // $res = \json_decode($ress,true);
        $res['code'] = 000000;
        if ($res['code']==000000) {
            $k = $phone.date('Y-m-d');
            $value = 1;
            RedisPackage::get($k,$value,600); 
            $key = $type.$phone;
            $true = RedisPackage::set($key,$param,600);
            return json(msg(1,'','发送成功'));
        }else{
            return json(msg(0,$res['msg'],'发送失败'));
        }
    }
    /**
     * 短信宝
     * 
     */
    public function sms(){
        $phone = input('phone');//手机号
        $type  = input('type');//类型 updatepwd-修改密码 updatephone-修改手机号 login-登录 register-注册账户 findpassword-找回密码
        if (empty($phone)) {
            return json(msg(0,'','手机号不能为空'));
        }
        if (empty($type)) {
            return json(msg(0,'','类型不能为空'));
        }
        RedisPackage::getInstance();
        $k = $phone.date('Y-m-d');
        $tre = RedisPackage::get($k);
        if ($tre) {
            if ($tre>3) {
                $k = $phone.date('Y-m-d');
                $value = $tre;
                RedisPackage::get($k,$value,'1800');
                return json(msg(0,'','对不起，请求次数太多，请30分钟后再试'));
            }else{
                $k = $phone.date('Y-m-d');
                $value += 1;
                RedisPackage::get($k,$value); 
            }
        }
        $statusStr = array(
            "0" => "短信发送成功",
            "-1" => "参数不全",
            "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
            "30" => "密码错误",
            "40" => "账号不存在",
            "41" => "余额不足",
            "42" => "帐户已过期",
            "43" => "IP地址限制",
            "50" => "内容含有敏感词",
            "51" => "手机号码不正确",
            );
        ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;)'); 
        $smsapi = 'http://api.smsbao.com/';
        $userinfo = userpassword();
        $user = $userinfo['user'];
        $pass = md5($userinfo['password']);
        $param= \strval(rand(1000,9999));
        $time = 5;
        $content = "【币天下】您的验证码是$param,在".$time."分钟内有效。";
        $sendurl = $smsapi.'sms?u='.$user.'&p='.$pass.'&m='.$phone.'&c='.urlencode($content);
        $sendurl = preg_replace("/ /", "%20", $sendurl);
        $result = file_get_contents($sendurl);
        if ($result==0) {
            // RedisPackage::getInstance();
            $key = $type.$phone;
            $true = RedisPackage::set($key,$param,600);
            return json(msg(1,'','发送成功'));
        }else{
            return json(msg(0,'',$statusStr[$result]));
        }
    }
    //币天下服务条款
    public function serviceagreement(){
        return $this->fetch('agreement');
    }
    
}
